package com.opesoft.pf.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.apache.log4j.Logger;

public class EntityManagerWrapper
{
	Logger log=Logger.getLogger(this.getClass());

	EntityManager em; // 用于产生Transaction的Session
	int level=-1; // 打开事务时所在的层次
	EntityTransaction transaction; // 打开的Transaction

	public EntityManagerWrapper(EntityManager em)
	{
		this.em=em;
	}

	public EntityManager getEntityManager()
	{
		return this.em;
	}

	public void beginTransaction()
	{
		if(this.level<0)
		{
			this.transaction=this.em.getTransaction();
			this.transaction.begin();
			this.level=Thread.currentThread().getStackTrace().length;
			log.debug("Begin Transaction : "+this.transaction.hashCode());
		}
	}

	/**
	 * 提交事务
	 * 
	 * @param commit
	 *            真为提交，假为回退
	 */
	public void commitTransaction(boolean commit)
	{
		if(this.level==Thread.currentThread().getStackTrace().length)
		{
			if(commit)
			{
				this.transaction.commit();
				log.debug("Commit Transaction : "+this.transaction.hashCode());
			}
			else
			{
				this.transaction.rollback();
				log.debug("Rollback Transacton : "+this.transaction.hashCode());
			}

			this.transaction=null;
			this.level=-1;
		}
	}
}
